#coding: utf8

"""
"""

import time
import threading
import sha
import random

session_timeout = 45 * 60

class _SessionInfo:
    def __init__(self, obj):
        self.obj = obj
        self.atime = time.time()

_sessions = {}
_sessions_lock = threading.Lock()

def _lock():
    _sessions_lock.acquire()

def _unlock():
    _sessions_lock.release()

def _cleanup():
# se asume que nos llaman con _sessions_lock held
    now = time.time()
    for sid in _sessions.keys():
        sinfo = _sessions[sid]
        if now > sinfo.atime + session_timeout:
            del _sessions[sid]

def _randomsid(obj):
    s = str(hash(obj)) + str(time.time()) + str(random.random())
    return sha.new(s).hexdigest()


def new(objid, obj):
    sid = _randomsid(objid)
    _lock()
    _cleanup()
    _sessions[sid] = _SessionInfo(obj)
    _unlock()
    return sid


def get(sid):
    _lock()
    _cleanup()
    if not _sessions.has_key(sid):
        _unlock()
        return None
    _sessions[sid].atime = time.time()
    o = _sessions[sid].obj
    _unlock()
    return o


def destroy(sid):
    _lock()
    _cleanup()
    if _sessions.has_key(sid):
        del _sessions[sid]
        _unlock()
